package com.caipiao.crawler.football;

import com.alibaba.fastjson.JSON;
import com.caipiao.crawler.mapper.LotteryFootballMapper;
import com.caipiao.crawler.mapper.LotteryNumberMapper;
import com.caipiao.crawler.model.LotteryFootball;
import com.caipiao.crawler.model.LotteryNumber;
import com.caipiao.util.DBTools;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.ibatis.session.SqlSession;
import us.codecraft.webmagic.ResultItems;
import us.codecraft.webmagic.Task;
import us.codecraft.webmagic.pipeline.Pipeline;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by adminitrator on 2018/7/28.
 */
public class FootballMatchPipeline implements Pipeline {

    private static Log log = LogFactory.getLog(FootballMatchPipeline.class);

    @Override
    public synchronized void process(ResultItems resultItems, Task task) {
        List<LotteryFootball> m = resultItems.get("modelList");
        log.info("pipe process:" + Thread.currentThread().getId());
        if(m == null) {
            return;
        }
        commit(m);
    }

    public void commit( List<LotteryFootball> list) {
        log.info("------------- FootballMatchPipeline commit开始-----------");
        //TODO 写数据库，需要判断不存在的情况才写入
        SqlSession session = DBTools.getSession();
        LotteryFootballMapper mapper = session.getMapper(LotteryFootballMapper.class);
        for(int i=0;i<list.size();i++) {
            int mid = list.get(i).getMid();
           int count =  mapper.selectCountByMid(list.get(i).getMid());
           if(count==0) {
               mapper.insertModel(list.get(i));
           }else{
               Map map = new HashMap();
               map.put("mid",list.get(i).getMid());
               map.put("status",list.get(i).getStatus());
               map.put("start_time",list.get(i).getStart_time());
               mapper.updateStatusByMid(map);
           }
        }
        session.commit();
        //TODO 如果第一次写入，触发更新判断是否中奖的逻辑

        session.close();
        log.info("------------- FootballMatchPipeline commit结束-----------");
    }

}
